import moment from "moment";
import { DeviceEventEmitter } from "react-native";

class LimitMessageQueue {
    constructor(max) {
        this.max = max;
        this._count = 0;
        this._pendingQueue = [];
    }

    push(obj, callback) {
        if(this._count >= this.max) {
            this._pendingQueue.pop();
            this._count -= 1;
        }
        this._pendingQueue.unshift(obj);
        this._count += 1;
        callback && callback();
    }

    toArray() {
        return this._pendingQueue;
    }

    clear() {
        this._count = 0;
        this._pendingQueue = [];
    }
}

let debug_topic = false;
let topic_queue = null;
let debug_flag = 0;
export function setTopicDebug() {
    topic_queue = new LimitMessageQueue(100);
    debug_topic = true;
}

export function isTopicDebug() {
    return debug_topic;
}

export function setTopicFilterFlag(flag, o) {
    if(o) {
        debug_flag |= flag;
    } else {
        debug_flag ^= flag;
    }
}

export function getTopicFilterFlag() {
    return debug_flag;
}

export function topic_debug_record(isSend, isRemote, topic, payload) {
    if(debug_topic && topic_queue) {
        topic_queue.push({isSend, isRemote, topic, payload, time: moment().format("MM-DD HH:mm:ss")}, ()=>{
            DeviceEventEmitter.emit("topic_debug");
        });
    }
}

export function query_topic_records() {
    if(debug_topic && topic_queue) {
        return topic_queue.toArray();
    } else {
        return null;
    }
}

export function closeTopicDebug() {
    debug_topic = false;
    topic_queue.clear();
    topic_queue = null;
}